<?php
/**
* Classe SGBD - Singleton
*
* 
*/
class SGBD {
    
    private static $_SGBD_connexion;
    private static $_SGBD_type;

    /**
     * Constructeur
     */
    private function __construct() {
        
        require('src/db_config.php'); // Data base connexion info
		
		try {
                  
            // Retrouve le type de sgbd
            switch($db_type) {
				
				case "pgsql":
				
					self::$_SGBD_type = "pg";
							 
					// Option port
					($db_port != -1) ? $port = " port=".$db_port : $port = "";
					
					// Création d'une instance de connexion
					self::$_SGBD_connexion = pg_connect(
						" host=".$db_server.$port. 
						" dbname=".$db_name.	
						" user=".$db_username. 
						" password=".$db_password			
						);
					break;			
				
				case "mysql":
				
					self::$_SGBD_type = "mysql";
							 
					// Option port
					($db_port != -1) ? $port = ":".$db_port : $port = "";
					
					// Création d'une instance de connexion
					self::$_SGBD_connexion = mysql_connect(
						$db_server.$port, 
						$db_username, 
						$db_password			
						);
					if(!mysql_select_db($db_name,self::$_SGBD_connexion)) throw new Exception("Erreur :".mysql_error());
					break;			
				
						
				default:
					throw new Exception("Le SGBD de type ".$db_tybe." n'a pas été reconnu");
				
			}			

        } catch (Exception $e) {
            throw new Exception("SGBD connection error: " . $e->getMessage());
        }
    }

    /**
     * Empêche la copie externe de l'instance
     */
    private function __clone() {
        throw new Exception('SGBD est un singleton, copie non autorisée');
    }

   	
	public static function query($request) {
	   
	   if(NULL === self::$_SGBD_connexion)           
           new self;
		switch(self::$_SGBD_type) {
			case "pg": 
			return pg_query(self::$_SGBD_connexion,$request);		
			
			case "mysql":
			return mysql_query($request,self::$_SGBD_connexion);
		}
	}
	
	public static function fetch($request_result) {
		
		 if(NULL === self::$_SGBD_connexion)           
           new self;
		switch(self::$_SGBD_type) {
			case "pg": 
			return pg_fetch_assoc($request_result);	
		
			case "mysql": 
			return mysql_fetch_assoc($request_result);	
		
		}
	}

}
?>
